package cn.com.captureNetPacket.dependThirdPartyImpl;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;

import cn.com.captureNetPacket.CaptureNetPacketService;
import cn.com.captureNetPacket.dependThirdParty.DependThirdPartyService;
import cn.com.captureNetPacket.model.DeviceStatus;
import cn.com.captureNetPacket.model.SignallingInfo;
import cn.com.captureNetPacket.util.JsonPathUtil;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@ConditionalOnProperty(name = "cnp.dependThirdParty.enable", havingValue = "true",matchIfMissing = false)
@Component
public class DependThirdPartyHuaweiImpl implements DependThirdPartyService{
	RestTemplate restTemplate = new RestTemplate();
	
	  
	 @Value("${cnp.dependThirdParty.connectUrl}")
	 private   String connectUrl;
//	该接口的请求消息体举例如下：

//	{"ccId":1,"vdnId":1}
//	{"message":"","retcode":"0","result":[{"agentId":201,"phone":"59001"},{"agentId":291,"phone":"40101"},{"agentId":330,"phone":"59002"}]}
	
	// 查询指定VDN下的座席电话号码
	private  String allAgentPhonesURL=connectUrl+"/cmsgateway/resource/real/agent/allagentphones";
	
	
	//查询指定坐席下的通话情况
	private  String agentPrivateCallsURL=connectUrl+"/cmsgateway/resource/real/agent/agentprivatecall";
	
//	public static  Map<String,String> agentDeviceMap=new ConcurrentHashMap<String, String>();
	/**
	 * 分机,工号
	 */
	BiMap<String,String> agentDeviceMap =null; 
	@Override
	public SignallingInfo improveAndPerfectSignallingInfo(SignallingInfo signallingInfo) {
		if(agentDeviceMap==null)return null;
		String agentId=null;
		agentId=agentDeviceMap.get(signallingInfo.getDeviceNumber());
		if(agentId==null)
			{
			log.info("分机 {} 没找到工号信息。",signallingInfo.getDeviceNumber());
			return signallingInfo;
			}
		signallingInfo.setAgentID(agentDeviceMap.get(signallingInfo.getDeviceNumber()));
		
		 List<String> listAllCalls=null;
		 listAllCalls=sendAgentPrivateCallsURLRequest("1","1",signallingInfo.getAgentID());
		 if(listAllCalls!=null) {
			 if( listAllCalls.size()>0)
			 signallingInfo.setCallUUID(listAllCalls.get(0));
		 }
		 else {
			 log.info("分机: {}  工号 :{}  没找到callid。",signallingInfo.getDeviceNumber(),signallingInfo.getAgentID());
		 }
		return signallingInfo;
	}

	@Override
	public SignallingInfo getSignallingInfo(SignallingInfo signallingInfo) {
		if(agentDeviceMap==null)return null;
		String agentId=null;
		agentId=agentDeviceMap.get(signallingInfo.getDeviceNumber());
		if(agentId==null)
			{
			log.info("分机 {} 没找到工号信息。",signallingInfo.getDeviceNumber());
			return signallingInfo;
			}
		signallingInfo.setAgentID(agentDeviceMap.get(signallingInfo.getDeviceNumber()));
		
		 List<String> listAllCalls=null;
		 listAllCalls=sendAgentPrivateCallsURLRequest("1","1",signallingInfo.getAgentID());
		 if(listAllCalls!=null) {
			 if( listAllCalls.size()>0)
			 signallingInfo.setCallUUID(listAllCalls.get(0));
		 }
		 else {
			 log.info("分机: {}  工号 :{}  没找到callid。",signallingInfo.getDeviceNumber(),signallingInfo.getAgentID());
		 }
		return signallingInfo;
	}
	
	
	//同步坐席和分机的绑定关系
	public void initDependThirdPartyServiceTask() {
		if(agentDeviceMap==null) {
			agentDeviceMap= HashBiMap.create();
			CaptureNetPacketService.getTaskService().execute(new Thread(new Runnable(){
				//调用Runnable接口
		    	public void run(){    		
		    	 while(true) {
		    	  try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						 log.error(" initSynAgentDeviceInfoTask :",e);
					}
		    		 
		    		 synAgentDeviceInfoTask();
		    		 
		    	 }
		    		
		    	}    	
		    }) );
		}
		
		
		
	}
	
			//同步坐席和分机的绑定关系
		public void synAgentDeviceInfoTask() {
			try {
			sendAllAgentPhonesRequest("1","1");
			}catch (Exception e) {
			log.error("synAgentDeviceInfoTask",e);
			}
			}
		/**
		 * 
			* <strong>Title: <strong>
			* <p>Description: 查找分机上登录的，坐席<p>
			* <p>Company: </p> 
			*<strong>Copyright:</strong> Copyright (c) 2019
			* @version: 1.0
			* @author  ASUS:augustWei
			* @date  2020 下午11:16:39
			* @param ccId
			* @param vdnId
		 */
	   private void sendAllAgentPhonesRequest(String ccId,String vdnId){
		   MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();        
		   map.add("ccId",ccId);
		   map.add("vdnId",vdnId);   
		   HttpHeaders headers = new HttpHeaders();
		   headers.setContentType(MediaType.APPLICATION_JSON_UTF8);        
		  HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(map, headers); 
		//  执行HTTP请求
		  ResponseEntity<String> responseEntity = restTemplate.postForEntity(allAgentPhonesURL, requestEntity , String.class );
		  String errorCode=JsonPathUtil.getValue(responseEntity.getBody(), "$.retcode");
		  if(!errorCode.equals("0"))
		  {
			log.warn("sendAllAgentPhonesRequest ，请求坐席登录分机信息错误， error :{}",errorCode);
			return ;
		  }
		  List<Map<String,String>> listAgentPhone=JsonPathUtil.getValue(responseEntity.getBody(), "$.result",List.class);
		  for (Map<String, String> map2 : listAgentPhone) {
			  try {
			  String phone= map2.get("phone");
			  if(agentDeviceMap.get(phone)!=null)
				  agentDeviceMap.remove(phone);
			  agentDeviceMap.put(phone, map2.get("agentId"));
			  }catch (Exception e) {
				  log.error("sendAllAgentPhonesRequest 坐席绑定分机解析异常",e);
			}
		}
	   }
	   
	   
	   
	   /**
	    * 
	   	* <strong>Title: <strong>
	   	* <p>Description: <p>
	   	* <p>Company: </p> 
	   	*<strong>Copyright:</strong> Copyright (c) 2019
	   	* @version: 1.0
	   	* @author  ASUS:augustWei
	   	* @date  2020 下午11:28:21
	   	* @param ccId
	   	* @param vdnId
	   	* @param agentId
	    */
	   private  List<String> sendAgentPrivateCallsURLRequest(String ccId,String vdnId,String agentId){
		   MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();        
		   map.add("ccId",ccId);
		   map.add("vdnId",vdnId);   
		   map.add("agentId",agentId);   
		   HttpHeaders headers = new HttpHeaders();
		   headers.setContentType(MediaType.APPLICATION_JSON_UTF8);        
		   HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(map, headers); 
		   //  执行HTTP请求
		   ResponseEntity<String> responseEntity = restTemplate.postForEntity(agentPrivateCallsURL, requestEntity , String.class );
		   String errorCode=JsonPathUtil.getValue(responseEntity.getBody(), "$.retcode");
		   if(!errorCode.equals("0"))
		   {
			   log.warn("sendAllAgentPhonesRequest ，请求坐席登录分机信息错误， error :{}",errorCode);
			   return null;
		   }
		   String responseStr=responseEntity.getBody();
		   log.info("sendAgentPrivateCallsURLRequest agentId : {} response callid: {}",agentId,responseStr);
		   List<String> listAllCalls=JsonPathUtil.getValue(responseStr, "$.result",List.class);
		   return listAllCalls;
	   }

	@Override
	public DeviceStatus waitDeviceStatus(String deviceNumber) {
		// TODO Auto-generated method stub
		return null;
	}

	 
}
